<template>
	<view>
		<u-button type="primary" text="微信授权登录" @click="login"></u-button>
	</view>
</template>

<script>
	import {
		loginApi
	} from "@/api/user"
	export default {
		data() {
			return {

			}
		},
		onLoad() {
			if (!this.isWechat()) {
				uni.showToast({
					title: '请使用微信网页浏览器打开',
					icon: 'none'
				})

				return;
			} else {
				this.checkWeChatCode()
			}
		},
		methods: {
			isWechat() {
				const ua = window.navigator.userAgent.toLowerCase();
				if (ua.match(/micromessenger/i) == 'micromessenger') {
					return true;
				} else {
					return false;
				}
			},
			getUrlCode(name) {
				return decodeURIComponent((new RegExp('[?|&]' + name + '=' + '([^&;]+?)(&|#|;|$)').exec(location.href) ||
					[, ''
					])[1]
					.replace(/\+/g, '%20')) || null
			},
			login() {
				if (!this.isWechat()) {
					uni.showToast({
						title: '请使用微信网页浏览器打开',
						icon: 'none'
					})

					return;
				}
				console.log(window.location.href);
				let local = encodeURIComponent(window.location.href);
				let appid = 'wxca0c462b619d3b6b'
				window.location.href =
					"https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
					appid +
					"&redirect_uri=" +
					local +
					"&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";

			},
			checkWeChatCode() {
				let code = this.getUrlCode('code')
				if (code) {
					console.log(code);
					this.getOpenidAndUserinfo(code)
				}
			},
			async getOpenidAndUserinfo(code) {
				const res = await loginApi({
					code
				})
				console.log(res);
			}
		}
	}
</script>

<style>

</style>